package com.bootdo.api;

import com.bootdo.common.controller.BaseController;
import com.bootdo.common.request.Result;
import com.bootdo.common.request.ResultCode;
import com.bootdo.common.utils.*;
import com.bootdo.crm.domain.CustomerDO;
import com.bootdo.crm.service.CustomerService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/crm")
public class CrmApiController extends BaseController {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private CustomerService customerService;



    @GetMapping("/list")
  //  @RequiresPermissions("crm:api:customer")
    public Result list(@RequestParam Map<String, Object> params){
        //查询列表数据
        Query query = new Query(params);
        List<CustomerDO> customerList = customerService.list(query);
        int total = customerService.count(query);
        PageUtils pageUtils = new PageUtils(customerList, total);
        return Result.success(pageUtils,"获取成功！");
    }
    /**
     * 保存
     */
    @PostMapping("/save")
  //  @RequiresPermissions("crm:api:add")
    public Result save(CustomerDO customer){
        try {
            customer.setCreateUserId(ShiroUtils.getUserId());
            customer.setCreateTime(TimeUtils.getStringTime());
            if(customerService.save(customer)>0){
                return Result.success("获取成功！");
            }
        }catch (Exception e){
            logger.error("【添加客户信息】报错："+e.getMessage());
            return Result.error(ResultCode.ERROR,"添加失败");
        }
        return Result.error(ResultCode.ERROR,"添加失败");
    }


    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("crm:api:edit")
    public Result update( CustomerDO customer){
        try {
            customer.setUpdateTime(TimeUtils.getStringTime());
            customerService.update(customer);
            return Result.success();
        }catch (Exception e){
            logger.error("【更新客户信息】报错："+e.getMessage());
            return Result.error(ResultCode.ERROR,"更新失败");
        }

    }

    @GetMapping("/edit/{customerId}")
    @RequiresPermissions("crm:api:edit")
    Result edit(@PathVariable("customerId") Integer customerId, Model model){
        CustomerDO customer = customerService.get(customerId);
        return Result.success(customer);
    }
}
